package com.huatai.verity.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @program: ht-system
 * @description: RSA加密工具
 * @author: songxiude
 * @create: 2023-07-20 14:39
 **/
public class RSAUtils {

	/**
	 * 公钥base64
	 */
	private static String puk ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCBU+dUDEZCyM4tGEbrW05+K58UW4N9OlDvIXpEOxrEBWPotTB1gTwLWKhhik0EKYdKDZxyPvil8Wmv9VdpA9TFaXUdW3gAuMOezFd2vDOKGOvSwbql6cWVzEFGva9nejB2dIDstCBME3wyokXJiCv593Ywnkd853bvk0E76/iifwIDAQAB";
	/**
	 * 加密
	 *
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String content) throws Exception {

		byte[] publicKeyBytes = puk.getBytes();
		X509EncodedKeySpec x = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBytes));
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey pubKey = keyFactory.generatePublic(x);
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);

		byte[] result = cipher.doFinal(content.getBytes("UTF-8"));
		return Base64.getEncoder().encodeToString(result);
	}

	/**
	 * 私钥base64
	 */
	private static String prk ="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIFT51QMRkLIzi0YRutbTn4rnxRbg306UO8hekQ7GsQFY+i1MHWBPAtYqGGKTQQph0oNnHI++KXxaa/1V2kD1MVpdR1beAC4w57MV3a8M4oY69LBuqXpxZXMQUa9r2d6MHZ0gOy0IEwTfDKiRcmIK/n3djCeR3zndu+TQTvr+KJ/AgMBAAECgYA+OtBSCgH4+sTyv/7IG0xeu8C1O/++T0RIfLRnhoUvk2RqwlzJ/eCVmRiUrsa2XQFDad9AvfpJZyuyxnxEBNrpXjqdH1CRLtP5GdE8GrP39jKbqu8qvSxXV1p2xNKSsKBOWkXbQF+ewZXBYAhRWNa7ks028o0Rg0ngZ05xHfjEOQJBANDR2Z9J/aTbZzBYZycCeD3CqzBkxYSl9CopjtGcBjziWZgsbKR8QyAQOWdTwv/f6A7XPhsHUfhiXdD7gAyfi8UCQQCejDsnrBaMr1XRaOlhUTpMZtgUkE3fAYrCXPa0RSF0e6NxldRQydjucw2AphQxlJWaIUiELQyklCEjCi9nagVzAkBrZNGAW4RISdJbCcwbQujmEn0KSXlPzC2zlWXvJUgL/flICujg+0tmbRGos2phQB1PrKEzM2OT07seJIppc5BlAkACy+5vMLXlHWKiIvua39fraRT+p9z3xgswins/isigSV4EruPj2OueqSDf2A4bIcfRxCyHSFQkwwgimhdj95bJAkEAxrqZ9+16o9GdseZKbWnfR5Rrf3idQRJJ2AgTDFUQnlw7WRXmr0t7uJpkqAeJEUy09Eji7vKrepCmMguxIaB4Fw==";
	public static String decrypt(String signEncrypt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		byte[] privateKeyBytes = prk.getBytes();
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyBytes));
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, priKey);

		byte[] result = cipher.doFinal(Base64.getDecoder().decode(signEncrypt));
		return new String(result);
	}

}
